<template>
	<view class="container" style="padding-bottom: 120rpx;">
		<!-- 使用uView的Subsection实现模式切换 -->
		<u-subsection 
			:list="sectionList" 
			:current="currentMode" 
			activeColor="#1989fa"
			inactiveColor="#606266"
			font-size="28rpx"
			@change="sectionChange"
		></u-subsection>

		<!-- 查询表单区域 -->
		<u--form ref="queryForm" :model="query" label-width="140rpx">
			<!-- PRG1模式显示厂别和线体，PRG2模式隐藏 -->
			<u-form-item label="车间" prop="plant">
				<uni-data-select 
					v-model="query.plant" 
					:localdata="plantList" 
					@change="selectChange('plant', query.plant)"
					style="flex: 1;" 
					:clear="false" 
					placeholder="请选择车间"
				></uni-data-select>
			</u-form-item>
			
			<u-form-item label="产线" prop="lineId">
				<uni-data-select 
					v-model="query.lineId" 
					:localdata="lineIdList" 
					@change="selectChange('lineId', query.lineId)"
					style="flex: 1;" 
					:clear="false" 
					placeholder="请选择产线"
				></uni-data-select>
			</u-form-item>
			
			<u-form-item label="工序" prop="process">
				<uni-data-select 
					v-model="query.process" 
					:localdata="processList"
					@change="selectChange('process', query.process)" 
					style="flex: 1;" 
					:clear="false"
					placeholder="请选择工序"
				></uni-data-select>
			</u-form-item>
			
			<u-form-item label="物料编码" prop="material">
				<uni-data-select 
					v-model="query.material" 
					:localdata="materialCodeList"
					@change="selectChange('material', query.material)" 
					style="flex: 1;" 
					:clear="false"
					placeholder="请选择物料编码"
				></uni-data-select>
			</u-form-item>
		</u--form>

		<!-- 物料列表展示区域 -->
		<view style="display: flex;flex-direction: column;gap: 20rpx;margin-top: 15rpx;">
			<uni-card v-for="(item, index) in materialList" :key="index">
				<template v-slot:title>
					<view style="padding: 15rpx 15rpx 10rpx;" v-if="currentMode === 0">
						<checkbox-group @change="handleAllChange">
							<checkbox 
								value="all" 
								:checked="selectAll" 
								style="transform:scale(0.9)"
							>
								全选/不全选
							</checkbox>
						</checkbox-group>
					</view>
					<gap :height="2" bgColor="#fcf493" />
				</template>
				
				<view>
					<!-- 物料名称 -->
					<view class="text-item" style="color: #398ade;font-weight: 600;font-size: 30rpx;">
						<text class="label">物料名称：</text>
						<text class="content">{{ item.MATERIAL_NAME }}</text>
					</view>
					
					<!-- 详细信息 -->
					<view class="item-top">
						<view class="left">
							<view class="text-item">
								<text class="label">料号：</text>
								<text class="content">{{ item.MATERIAL }}</text>
							</view>
							
							<!-- PRG1模式显示线体信息 -->
							<view class="text-item">
								<text class="label">线体：</text>
								<text class="content">{{ item.LINE_ID }}</text>
							</view>
							
							<view class="text-item">
								<text class="label">工序：</text>
								<text class="content">{{ item.PROCESS }}</text>
							</view>
							
							<view class="text-item">
								<text class="label">工单：</text>
								<text class="content">{{ item.WO }}</text>
							</view>
							
							<!-- PRG2模式额外显示派发类型 -->
							<view class="text-item" v-if="currentMode === 1">
								<text class="label">派发类型：</text>
								<text class="content">自动派发</text>
							</view>
						</view>
						
						<view class="right">
							<checkbox-group v-if="currentMode === 0" @change="handleChange($event, index)">
								<checkbox 
									:value="'material' + index" 
									:checked="item.checked" 
									style="transform:scale(1.1)" 
								/>
							</checkbox-group>
							<checkbox-group v-else @change="handleChangeNotOrder($event, index)">
								<checkbox 
									:value="'material' + index" 
									:checked="item.checked" 
									style="transform:scale(1.1)" 
								/>
							</checkbox-group>
						</view>
					</view>
				</view>
			</uni-card>
		</view>

		<u-toast ref="uToast"></u-toast>
		
		<!-- 底部补料按钮 -->
		<view class="commonButton">
			<u-button
				v-if="currentMode === 0"
				type="warning" 
				style="font-size: 36rpx;width: 100%;" 
				@click="replenish"
				:loading="btn.loading"
			>
				补料
			</u-button>
			<u-button
				v-if="currentMode === 1"
				type="warning" 
				style="font-size: 36rpx;width: 100%;" 
				@click="checkStorage"
				:disabled="this.materialList.filter(item => item.checked === true).length === 0"
			>
				查询库存
			</u-button>
		</view>
	</view>
</template>

<script>
	import { mapMutations } from 'vuex'
	import {
		frequentAPI,
		replenishAPI,
		getListNotOrderAPI
	} from '@/api/work/usageAPIList.js'
	import { uniCard } from '@dcloudio/uni-ui'
	import uniDataSelect from '@dcloudio/uni-ui/lib/uni-data-select/uni-data-select.vue'
	import gap from '@/components/gap/Gap'
	// 引入uView的Subsection组件

	export default {
		components: {
			uniCard,
			uniDataSelect,
			gap
		},
		data() {
			return {
				// 分段器数据
				sectionList: ['领料单发料','工单发料(无领料单)'],
				currentMode: 0, // 默认PRG1模式
				query: {
					plant: '',
					lineId: '',
					process: '',
					material: ''
				},
				selectAll: false,
				materialList: [''],
				materialCodeList: [],
				plantList: [],
				lineIdList: [],
				processList: [],
				btn: {
					loading: false
				}
			};
		},
		mounted() {
			// this.getList()
		},
		methods: {
			...mapMutations(['SET_MATERIAL_DATA']),
			sectionChange(index) {
				this.currentMode = index;
			},
			// 获取初始物料列表
			async getList() {
				try {
					const res = await frequentAPI()
					if (res.message.code === 200) {
						this.materialList = res.data.map(item => ({
							...item,
							checked: false // 初始化复选框状态
						}))
						
						// 初始化厂别列表（去重处理）
						this.plantList = [...new Map(
							res.data.map(item => [{
								text: item.PLANT,
								value: item.PLANT
							}, item.PLANT])
						).values()]
					}
				} catch (error) {
					console.error('获取物料列表失败:', error)
					this.$refs.uToast.show({
						type: 'error',
						message: '数据加载失败'
					})
				}
			},
			
			// 获取物料列表(无领料单)
			async getListNotOrder() {
				try {
					// const res = await getListNotOrderAPI()
					// if (res.returnCode === '1') {
						// this.materialList = res.returnData.data.map(item => ({
						// 	...item,
						// 	checked: false
						// }))
						
						// 初始化厂别列表（去重处理）
						// this.plantList = [...new Map(
						// 	res.data.map(item => [{
						// 		text: item.PLANT,
						// 		value: item.PLANT
						// 	}, item.PLANT])
						// ).values()]
						this.materialList = [{
							"CLASSDATE": "2025-03-21",
							"DOC_NO": "MO012501152711-1",
							"ID": 34978,
							"IS_AGV": "Y",
							"LINEID_NAME": "总装15线",
							"LINE_ID": "HZ15",
							"MATERIAL": "82211010900149",
							"MATERIAL_NAME": "前网 共聚PP 注塑 8寸 棕色4259C 零件重量0.191KG FJ20-23DP18 (829209000179)",
							"MATERIAL_TYPE": "xx-1",
							"PHASE": "ALL->Assembly",
							"PLANT": "HH01",
							"PROCESS": "100909",
							"QTY": 10,
							"SCH_TIME": "2025-02-08 16:00:57",
							"SLOC": "W03005",
							"SLOC_TO": "W03005",
							"STATUS": "WAIT_ISSUE",
							"TRACK": "DEFAULT_VIRTUAL_TRACK",
							"UNIT": "1",
							"WO": "MO012501152711-1",
							"VENDOR": "xx-1",
							"checked": false
						}, {
							"CLASSDATE": "2025-03-21",
							"DOC_NO": "MO012501152711-2",
							"ID": 34979,
							"IS_AGV": "Y",
							"LINEID_NAME": "总装14线",
							"LINE_ID": "HZ16",
							"MATERIAL": "82211010800150",
							"MATERIAL_NAME": "前网 共聚PP 注塑 8寸 棕色4259C 零件重量0.191KG FJ20-23DP18 (829209000179)",
							"MATERIAL_TYPE": "xx-1",
							"PHASE": "ALL->Assembly",
							"PLANT": "HH02",
							"PROCESS": "100910",
							"QTY": 10,
							"SCH_TIME": "2025-02-08 16:00:57",
							"SLOC": "W03005",
							"SLOC_TO": "W03005",
							"STATUS": "WAIT_ISSUE",
							"TRACK": "DEFAULT_VIRTUAL_TRACK",
							"UNIT": "1",
							"WO": "MO012501152711-1",
							"VENDOR": "xx-1",
							"checked": false
						}]
						
						this.plantList = [...new Map(this.materialList.map(item => {
							return {
								text: item.PLANT,
								value: item.PLANT
							}
						}).map(item => [item.value, item])).values()]
					// }
				} catch(error) {
					console.error('获取物料列表失败:', error)
					this.$refs.uToast.show({
						type: 'error',
						message: '数据加载失败'
					})
				}
			},
			
			// 查询库存跳转
			checkStorage() {
				const checkMaterial = this.materialList.filter(item => item.checked === true)[0]
				console.log(checkMaterial)
				this.SET_MATERIAL_DATA(checkMaterial)
				uni.navigateTo({
					url: '/pages/work/manual/inventoryQuery'
				})
			},
			
			// 选择器变更处理
			async selectChange(key, value) {
				// 重置下级选择器
				if (key === 'plant') {
					this.query.lineId = ''
					this.query.process = ''
					this.query.material = ''
					this.lineIdList = []
					this.processList = []
					this.materialCodeList = []
				} else if (key === 'lineId') {
					this.query.process = ''
					this.query.material = ''
					this.processList = []
					this.materialCodeList = []
				} else if (key === 'process') {
					this.query.material = ''
					this.materialCodeList = []
				}

				// 构建查询参数
				const submitForm = {
					PLANT: this.query.plant,
					LINE_ID: this.query.lineId,
					PROCESS: this.query.process,
					MATERIAL: this.query.material
				}

				try {
					const { api, getSuccess, getDataSource } = this.currentMode === 0 
						? { 
								api: frequentAPI,
								getSuccess: res => res.message.code === 200,
								getDataSource: res => res.data 
							}
						: { 
								api: getListNotOrderAPI,
								getSuccess: res => res.returnCode === '1',
								getDataSource: res => res.returnData.data 
							}
				
					const res = await api(submitForm)
					if (getSuccess(res)) {
						const dataSource = getDataSource(res)
						this.materialList = dataSource.map(item => ({ ...item, checked: false }))
						
						// 根据当前变更的字段更新对应下拉列表
						switch (key) {
							case 'plant':
								this.lineIdList = [...new Map(dataSource.map(item => {
									return {
										text: item.LINE_ID,
										value: item.LINE_ID
									}
								}).map(item => [item.value, item])).values()]
								break
							case 'lineId':
								this.processList = [...new Map(dataSource.map(item => {
									return {
										text: item.PROCESS,
										value: item.PROCESS
									}
								}).map(item => [item.value, item])).values()]
								break
							case 'process':
								this.materialCodeList = [...new Map(dataSource.map(item => {
									return {
										text: item.MATERIAL,
										value: item.MATERIAL
									}
								}).map(item => [item.value, item])).values()]
								break
						}
					}
				} catch (error) {
					console.error('筛选数据失败:', error)
				}
			},
			
			// 补料操作
			async replenish() {
				// 获取选中的物料
				const selectedItems = this.materialList.filter(item => item.checked)
				if (selectedItems.length === 0) {
					return this.$refs.uToast.show({
						type: 'warning',
						message: '请选择需要补料的物料'
					})
				}

				// 处理请求数据
				const submitData = selectedItems.map(({ checked, ...rest }) => ({
					...rest,
					mode: this.currentMode // 添加模式标识
				}))

				try {
					this.btn.loading = true
					const res = await replenishAPI(submitData)
					if (res.message.code === 200) {
						this.$refs.uToast.show({
							type: 'success',
							message: res.returnReason || '补料成功'
						})
						// 重置选择状态
						this.materialList.forEach(item => item.checked = false)
						this.selectAll = false
					} else {
						this.$refs.uToast.show({
							type: 'error',
							message: res.returnReason || '补料失败'
						})
					}
				} catch (error) {
					console.error('补料请求失败:', error)
					this.$refs.uToast.show({
						type: 'error',
						message: '网络错误，补料失败'
					})
				} finally {
					this.btn.loading = false
				}
			},
			
			// 全选/全不选处理
			handleAllChange(e) {
				const isAllChecked = e.detail.value.includes('all')
				this.selectAll = isAllChecked
				this.materialList.forEach(item => {
					item.checked = isAllChecked
				})
			},
			
			// 单个选择处理
			handleChange(e, index) {
				const isChecked = e.detail.value.length > 0
				this.materialList[index].checked = isChecked
				
				// 检查是否全选
				this.selectAll = this.materialList.every(item => item.checked)
			},
			handleChangeNotOrder(e, index) {
				const isChecked = e.detail.value.length > 0
				this.materialList.forEach(item => item.checked = false)
				this.materialList[index].checked = isChecked
			}
		},
		watch: {
			// 模式切换时重置表单和列表
			currentMode(newVal) {
				// 重置查询条件
				this.query = {
					plant: '',
					lineId: '',
					process: '',
					material: ''
				}
				// 重置下拉列表
				this.lineIdList = []
				this.processList = []
				this.materialCodeList = []
				// 重新加载数据
				if (newVal === 0) {
					this.getList()
				} else {
					this.getListNotOrder()
				}
			}
		}
	}
</script>

<style lang="scss">
	.commonButton {
		width: 100%;
		display: flex;
		gap: 20rpx;
		position: fixed;
		left: 0;
		bottom: 0;
		box-sizing: border-box;
		padding: 15rpx;
		justify-content: space-between;
		background-color: #fff;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	::v-deep .uni-card {
		margin: 0 !important;
		padding: 0 !important;
		border-radius: 10rpx;
	}

	.item-top {
		width: 100%;
		display: flex;
		justify-content: space-between;
		padding: 10rpx 15rpx;

		.left {
			flex: 8;
			display: flex;
			flex-direction: column;
			align-items: flex-start;
			gap: 8rpx;
		}

		.right {
			flex: 2;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
		}

		.text-item {
			display: flex;
			width: 100%;
			word-wrap: break-word;
			overflow-wrap: break-word;
			color: #000;
			font-size: 28rpx;
			line-height: 1.5;

			.label {
				white-space: nowrap;
				color: #666;
				min-width: 120rpx;
			}

			.content {
				flex: 1;
				word-wrap: break-word;
				overflow-wrap: anywhere;
			}
		}
	}

	// 适配u-subsection的样式
	::v-deep .u-subsection {
		border-radius: 8rpx;
		background-color: #f5f7fa;
	}

	::v-deep .u-subsection__item {
		height: 70rpx;
		line-height: 70rpx;
	}
	::v-deep .u-subsection--button {
		height: auto;
	}

	.uni-card {
		background-color: #fefecc;
		border-color: #fcf493;
		margin-bottom: 20rpx !important;
	}
</style>